import React from 'react';
import {connect} from 'react-redux';
import { Form, Card, Button, message } from 'antd';
import { deepCopy , messages } from "share/common";
import Skeleton from 'components/skeleton';
import airlineConfigService from './airline-config.service';
import FormItemAirlineVendor from './components/form-item-airline-vendor';

class AirlineConfigVendor extends React.Component {
  constructor() {
    super();
    this.state = {
      loading: true,
      submitting: false,
      vendorList: []
    };
  }
  componentDidMount = () => {
    const { companyOID } = this.props;
    airlineConfigService.getVendorList(companyOID)().then((res) => {
      if (res.data.code === 200) {
        if (res.data.body.length > 0) {
          this.setState({
            vendorList: res.data.body
          });
        } else {
          message.info(messages('supplier.key266')/*暂无数据*/);
        }
      }
    }).finally(() => {
      this.setState({ loading: false });
    });
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this.setState({ submitting: true });
    this.props.form.validateFields((error, values) => {
      const { companyOID } = this.props;
      const data = deepCopy(values);
      Object.keys(data).forEach((attr) => {
        delete data[attr].vendorEnabled
        data[attr].account = JSON.stringify(data[attr].account);
      })
      const vendors = Object.values(data);
      airlineConfigService.registerCompany(companyOID)({vendors})
        .then((res) => {
          if (res.data.code !== 200) return Promise.reject();
          return message.success(messages('common.operate.success')/*操作成功*/);
        })
        .finally(() => {
          this.setState({ submitting: false });
        });
    });
  }
  render = () => {
    const { getFieldDecorator } = this.props.form;
    const {submitting} = this.state;
    return (<div className="airline-config-container">
      {this.state.loading && <Skeleton />}
      <Form onSubmit={this.handleSubmit}>
        {this.state.vendorList.map(vendorInfo =>
          (<Form.Item>
            {getFieldDecorator(String(vendorInfo.vendorCode), {
              initialValue: vendorInfo
            })(
              <FormItemAirlineVendor />
            )}
          </Form.Item>)
        )}
        {this.state.vendorList.length > 0 && (
          <Form.Item>
            <Button type="primary" loading={submitting} htmlType="submit">{messages('supplier.key250')/*保存配置*/}</Button>
          </Form.Item>
        )}
      </Form>
    </div>);
  }
}

function mapStateToProps() {
  return {};
}
AirlineConfigVendor.propTypes = {
  companyOID: React.PropTypes.string
};

const WrappedAirlineConfigVendor = Form.create()(AirlineConfigVendor);
export default connect(mapStateToProps)(WrappedAirlineConfigVendor);
